package com.iuv.shortpromotion.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsResponse;
import com.iuv.shortpromotion.domain.DemoSmsPromotionTbl;
import com.iuv.shortpromotion.repository.DemoSmsPromotionTblRepository;
import com.iuv.shortpromotion.service.DemoSmsPromotionService;
import com.iuv.shortpromotion.util.ShortPromotionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

@Service("demoSmsPromotionService")
public class DemoSmsPromotionServiceImpl implements DemoSmsPromotionService {
    /**
     * 签名模板
     */
    private static String SIGN_NAME = "深圳市艾优威科技有限公司";
    @Autowired
    private DemoSmsPromotionTblRepository demoSmsPromotionTblRepository;
    @Override
    public Page<DemoSmsPromotionTbl> listSearch(DemoSmsPromotionTbl demoSmsPromotionTbl, Pageable pageable) {
        Specification<DemoSmsPromotionTbl> specification = new Specification<DemoSmsPromotionTbl>() {
            @Override
            public Predicate toPredicate(Root<DemoSmsPromotionTbl> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                //活动名称模糊查询
                if (StringUtils.isNoneBlank(demoSmsPromotionTbl.getPromotionName())) {
                    list.add(criteriaBuilder.like(root.get("promotionName").as(String.class), "%" + demoSmsPromotionTbl.getPromotionName() + "%"));
                }
                //推送号码模糊查询
                if (StringUtils.isNoneBlank(demoSmsPromotionTbl.getPushMobile())) {
                    list.add(criteriaBuilder.like(root.get("pushMobile").as(String.class), "%" + demoSmsPromotionTbl.getPushMobile() + "%"));
                }
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        };
        //分页查询
        return demoSmsPromotionTblRepository.findAll(specification, pageable);
    }

    @Override
    public DemoSmsPromotionTbl insert(DemoSmsPromotionTbl demoSmsPromotionTbl) {
        Date now = new Date();
        demoSmsPromotionTbl.setCreateTime(now);
        demoSmsPromotionTbl = demoSmsPromotionTblRepository.save(demoSmsPromotionTbl);
        return demoSmsPromotionTbl;
    }

    @Override
    public void save(DemoSmsPromotionTbl demoSmsPromotionTbl) {
        demoSmsPromotionTblRepository.save(demoSmsPromotionTbl);
    }

    @Override
    public DemoSmsPromotionTbl update(DemoSmsPromotionTbl demoSmsPromotionTbl) {
        DemoSmsPromotionTbl exitDemoSmsPromotionTblOptional = findByPromotionId(demoSmsPromotionTbl.getPromotionId());
        if (exitDemoSmsPromotionTblOptional != null) {
            if (demoSmsPromotionTbl.getPromotionName() != null) {
                exitDemoSmsPromotionTblOptional.setPromotionName(demoSmsPromotionTbl.getPromotionName());
            }
            if (demoSmsPromotionTbl.getCreateTime() != null) {
                exitDemoSmsPromotionTblOptional.setCreateTime(demoSmsPromotionTbl.getCreateTime());
            }
            if (demoSmsPromotionTbl.getEndTime() != null) {
                exitDemoSmsPromotionTblOptional.setEndTime(demoSmsPromotionTbl.getEndTime());
            }
            if (demoSmsPromotionTbl.getPushMobile() != null) {
                exitDemoSmsPromotionTblOptional.setPushMobile(demoSmsPromotionTbl.getPushMobile());
            }
            /**
             * 如果已申请模板，则内容不允许修改
             */
            if (StringUtils.trimToNull(demoSmsPromotionTbl.getTemplateCode()) == null && demoSmsPromotionTbl.getPushContents() != null) {
                exitDemoSmsPromotionTblOptional.setPushContents(demoSmsPromotionTbl.getPushContents());
            }
            if (demoSmsPromotionTbl.getPushStatus() != null) {
                exitDemoSmsPromotionTblOptional.setPushStatus(demoSmsPromotionTbl.getPushStatus());
            }
            if (demoSmsPromotionTbl.getErrorMessage() != null) {
                exitDemoSmsPromotionTblOptional.setErrorMessage(demoSmsPromotionTbl.getErrorMessage());
            }
            if (demoSmsPromotionTbl.getTemplateCode() != null) {
                exitDemoSmsPromotionTblOptional.setTemplateCode(demoSmsPromotionTbl.getTemplateCode());
            }
            if (demoSmsPromotionTbl.getLastPushTime() != null) {
                exitDemoSmsPromotionTblOptional.setLastPushTime(demoSmsPromotionTbl.getLastPushTime());
            }
            demoSmsPromotionTblRepository.save(exitDemoSmsPromotionTblOptional);
        }
        return exitDemoSmsPromotionTblOptional;
    }

    @Override
    public void delete(Integer promotionId) {
        demoSmsPromotionTblRepository.deleteById(promotionId);
    }

    @Override
    public DemoSmsPromotionTbl findByPromotionId(Integer promotionId) {
        Optional<DemoSmsPromotionTbl> optional =  demoSmsPromotionTblRepository.findById(promotionId);
        return optional.get();
    }

    @Override
    public boolean checkPromotionEnd(DemoSmsPromotionTbl demoSmsPromotionTbl) {
        Date startTime = demoSmsPromotionTbl.getStartTime();
        Date endTime = demoSmsPromotionTbl.getEndTime();
         Integer timeStatus = checkTimeStatus(startTime, endTime);
        if (timeStatus == 2) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 群发推广短信
     */
    @Override
    public void sendBatchSms(DemoSmsPromotionTbl demoSmsPromotionTbl) {
        //
        String[] phoneNumberList = StringUtils.split(demoSmsPromotionTbl.getPushMobile(), ",");
        String phoneNumberJson = JSONUtils.toJSONString(Arrays.asList(phoneNumberList));
        String signNameJson = makeBatchSignNameJson(SIGN_NAME, phoneNumberList.length);
        String templateParamJson = "[{},{}]";
        SendBatchSmsResponse sendBatchSmsResponse = ShortPromotionUtil.sendBatchSms(phoneNumberJson, signNameJson, demoSmsPromotionTbl.getTemplateCode(), templateParamJson);
        if (sendBatchSmsResponse != null || "OK".equalsIgnoreCase(sendBatchSmsResponse.getCode())) {
            //修改数据库
            demoSmsPromotionTbl.setPushStatus(1);
            demoSmsPromotionTbl.setLastPushTime(new Date());
            demoSmsPromotionTbl.setErrorMessage(sendBatchSmsResponse.getMessage());
        } else {
            demoSmsPromotionTbl.setPushStatus(0);
            demoSmsPromotionTbl.setErrorMessage(sendBatchSmsResponse.getMessage());
        }
       update(demoSmsPromotionTbl);
    }
    /**
     * 检查当前时间与所给时间段所处状态 0：当前时间在所给时间段之前 1：当前时间在所有时间段内 2：当前时间在所级时间段之后
     *
     * @param startTime
     * @param endTime
     * @return
     */
    private  Integer checkTimeStatus(Date startTime, Date endTime)
    {
        Integer status = null;
        if (startTime != null && endTime != null)
        {
            Date now = new Date();
            if (now.before(startTime))
            {
                status = 0;
            }
            else if (now.after(startTime) && now.before(endTime))
            {
                status = 1;
            }
            else if (now.after(endTime))
            {
                status = 2;
            }
        }
        return status;
    }
    /**
     * 生成批量模板Json
     * @param signName
     * @param singCount
     * @return
     */
    private String makeBatchSignNameJson(String signName, int singCount) {
        List<String> results = new ArrayList<>();
        for (int i = 0; i< singCount; i++) {
            results.add(signName);
        }
        return JSONUtils.toJSONString(results);
    }
}
